import snap7
import time
from snap7 import util

ip_address = '192.168.0.120'
rack = 0
slot = 1

plc = snap7.client.Client()
plc.connect(ip_address, rack, slot)

try:
    # 读取DB11.DBW2 (假设为牵引机设定拉力)
    data = plc.db_read(11, 0, 8)
    counter = util.get_int(data, 2)  # 从第2字节开始解析INT (DBW2)
    print(f"牵引机设定拉力: {counter}")

    time.sleep(1)

    # 读取MD2024 (牵引力)
    data_md2024 = plc.mb_read(2024, 4)  # 从MB2024开始读取4字节
    traction_force = util.get_dint(data_md2024, 0)
    print(f"牵引力: {traction_force}")

    # 读取MD3076 (型材总长度)
    data_md3076 = plc.mb_read(3076, 4)  # 从MB3076开始读取4字节
    total_length = util.get_dint(data_md3076, 0)
    print(f"型材总长度: {total_length}")

except Exception as e:
    print(f"发生错误: {e}")

finally:
    # 只在对象有效时断开连接和销毁
    if plc and hasattr(plc, 'get_connected'):
        if plc.get_connected():
            plc.disconnect()
        # 确保只调用一次destroy()
        if hasattr(plc, 'destroy'):
            plc.destroy()
            # 释放引用，避免析构时再次调用
            plc = None

    print("已断开连接并清理资源")